<template>
  <div class="spreadsheet-container">
    <div class="toolbar">
      <button @click="importExcel" class="btn" :disabled="isLoading">
        <span v-if="isLoading" class="loading-spinner"></span>
        {{ isLoading ? "导入中..." : "导入 Excel" }}
      </button>
      <button @click="exportExcel" class="btn">导出 Excel</button>
      <button @click="saveToLocal" class="btn btn-save">临时保存</button>
      <button @click="loadFromLocal" class="btn btn-load">加载保存数据</button>
      <button @click="clearSheet" class="btn btn-danger">清空表格</button>
    </div>
    <div id="spreadsheet" ref="spreadsheetRef"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import Spreadsheet from "x-data-spreadsheet";
import * as XLSX from "xlsx";
import ExcelJS from "exceljs";
import tinycolor from "tinycolor2";

// 设置中文语言
Spreadsheet.locale("zh-cn", {
  toolbar: {
    undo: "撤销",
    redo: "重做",
    paintformat: "格式刷",
    clearformat: "清除格式",
    format: "数据格式",
    font: "字体",
    fontSize: "字号",
    fontBold: "粗体",
    fontItalic: "斜体",
    underline: "下划线",
    strike: "删除线",
    textColor: "文字颜色",
    fillColor: "填充颜色",
    border: "边框",
    merge: "合并单元格",
    align: "对齐方式",
    valign: "垂直对齐",
    textwrap: "自动换行",
    freeze: "冻结",
    autofilter: "自动筛选",
    formula: "函数",
    more: "更多",
  },
  contextmenu: {
    copy: "复制",
    cut: "剪切",
    paste: "粘贴",
    pasteValue: "粘贴值",
    pasteFormat: "粘贴格式",
    insertRow: "插入行",
    insertColumn: "插入列",
    deleteRow: "删除行",
    deleteColumn: "删除列",
    deleteCell: "删除",
    clearCell: "清除",
  },
  format: {
    normal: "常规",
    text: "文本",
    number: "数值",
    percent: "百分比",
    rmb: "人民币",
    usd: "美元",
    date: "日期",
    time: "时间",
    datetime: "日期时间",
    duration: "持续时间",
  },
  formula: {
    sum: "求和",
    average: "平均值",
    max: "最大值",
    min: "最小值",
    concat: "字符串连接",
  },
});

const STORAGE_KEY = "spreadsheet_temp_data";

const props = defineProps({
  initialData: {
    type: Array,
    default: () => [[]],
  },
});

const emit = defineEmits(["update:data"]);

const spreadsheetRef = ref(null);
let spreadsheet = null;
const isLoading = ref(false);
const fileInput = ref(null);

// 初始化电子表格
const initSpreadsheet = async () => {
  try {
    await nextTick();
    if (!spreadsheetRef.value) return;

    spreadsheet = new Spreadsheet("#spreadsheet", {
      mode: "edit",
      showBottomBar: false ,// false
      showToolbar: true,
      showGrid: true,
      view: {
        height: () => document.documentElement.clientHeight - 100,
        width: () => document.documentElement.clientWidth - 40,
      },
      // 基础配置
      defaultColAlign: "left",
      defaultRowAlign: "middle",
      defaultColWidth: 120, // 增加默认列宽
      defaultRowHeight: 28, // 增加默认行高
      // 初始行列设置
      row: { len: 5000, height: 28 }, // 默认5000行，增加默认行高
      col: { len: 26, width: 120 }, // 默认26列 (A-Z)，增加默认列宽
      // 样式配置
      style: {
        bgcolor: "#ffffff",
        align: "left",
        valign: "middle",
        textwrap: false,
        strike: false,
        underline: false,
        color: "#0a0a0a",
        font: {
          name: "Arial",
          size: 10,
          bold: false,
          italic: false,
        },
        format: "text",
      },
      // 其他配置
      showFormulaBar: true,
      showStatusBar: true,
      showContextMenu: true,
      // 中文语言配置
      settings: {
        language: "zh-cn",
        locale: "zh-cn",
        format: {
          date: "YYYY-MM-DD",
          datetime: "YYYY-MM-DD HH:mm:ss",
        },
      },
    });

    loadFromLocal();

    console.log("电子表格初始化成功");
  } catch (error) {
    console.error("电子表格初始化失败:", error);
  }
};

// 获取数据中的最大行数
const getMaxRow = (data) => {
  if (!data || !data[0] || !data[0].rows) return 0;

  let maxRow = 0;
  const rows = data[0].rows;
  Object.keys(rows).forEach((key) => {
    if (key !== "len") {
      maxRow = Math.max(maxRow, parseInt(key));
    }
  });
  return maxRow;
};

// 监听数据变化
const watchData = () => {
  if (spreadsheet) {
    const currentData = spreadsheet.getData();
    // 检查是否需要增加行数
    const maxRow = getMaxRow(currentData);
    if (maxRow > spreadsheet.options.row.len) {
      // 限制最大行数为1000
      spreadsheet.options.row.len = Math.min(Math.ceil(maxRow * 1.2), 1000);
    }
    emit("update:data", currentData);
  }
};

onMounted(() => {
  initSpreadsheet();
  // 添加数据变化监听
  if (spreadsheet) {
    spreadsheet.on("cell-selected", watchData);
    spreadsheet.on("cell-edited", watchData);
  }
});

function convertMergeDataToArray(input) {
  const result = [];

  for (const key in input) {
    if (input.hasOwnProperty(key)) {
      const model = input[key].model;
      const startCell = key;
      const endCell = `${String.fromCharCode(64 + model.right)}${model.bottom}`;
      result.push(`${startCell}:${endCell}`);
    }
  }

  return result;
}

// 文件处理函数
const handleFileChange = async (event) => {
  try {
    const file = event.target.files && event.target.files[0];
    console.log("选择文件:", file);
    if (!file) {
      console.warn("未选择文件");
      return;
    }

    console.log("开始处理文件:", file.name);
    await importExcel(file);
  } catch (error) {
    console.error("文件处理错误:", error);
  } finally {
    // 重置文件输入，允许选择同一文件
    if (event.target) {
      event.target.value = "";
    }
  }
};

const readExcelFile = (file) => {
  console.log("读取文件:", file);
  //如果格式是 不是 .xlsx 提示请转换格式
  if (!file.name.endsWith(".xlsx")) {
    alert("请转换为 .xlsx 格式的 Excel 文件");
    return;
  }
  return new Promise((resolve, reject) => {
    if (!(file instanceof File)) {
      reject(new TypeError("提供的文件不是有效的 File 对象"));
      return;
    }

    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const buffer = e.target.result;
        const workbook = new ExcelJS.Workbook();
        await workbook.xlsx.load(buffer);
        resolve(workbook);
      } catch (error) {
        reject(error);
      }
    };

    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);
  });
};

// 文件读取函数
const selectAndReadExcelFile = () => {
  return new Promise((resolve, reject) => {
    // 创建一个隐藏的文件输入框
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".xlsx, .xls"; // 限制文件类型为 Excel 文件

    // 监听文件选择事件
    input.onchange = async (event) => {
      const file = event.target.files && event.target.files[0];
      if (!file) {
        reject(new Error("未选择文件"));
        return;
      }

      console.log("选择的文件:", file);

      // 调用 readExcelFile 方法读取文件
      try {
        const workbook = await readExcelFile(file);
        resolve(workbook);
      } catch (error) {
        reject(error);
      }
    };

    // 模拟点击文件输入框
    input.click();
  });
};
// 列号转换函数
const numberToColumn = (num) => {
  let result = "";
  while (num > 0) {
    num--;
    result = String.fromCharCode(65 + (num % 26)) + result;
    num = Math.floor(num / 26);
  }
  return result || "A";
};

// Excel导入函数
const importExcel = async () => {
  try {
    const workbook = await selectAndReadExcelFile();
    const worksheet = workbook.worksheets[0];
    if (!worksheet) {
      throw new Error("未找到有效的工作表");
    }

    // 初始化为正确的格式，注意索引从0开始
    const data = {
      name: worksheet.name || "Sheet1",
      freeze: "A1", // 添加原表中的freeze属性
      rows: { len: 5000 }, // 与原表保持一致
      cols: { len: 26 }, // 与原表保持一致
      styles: [],
      merges: [],
      validations: [], // 添加原表中的validations属性
      autofilter: {}, // 添加原表中的autofilter属性
    };

    // 样式映射，用于重用相同的样式
    const styleMap = new Map();
    // 创建一个集合来跟踪合并单元格区域中的非左上角单元格
    const mergedCellsSet = new Set();
    // 新增一个映射，用于记录合并单元格区域的边界信息
    const mergeBoundaries = new Map();

    // 处理合并单元格
    if (worksheet._merges) {
      Object.entries(worksheet._merges).forEach(([key, cellInfo]) => {
        if (cellInfo?.model) {
          const { top, left, bottom, right } = cellInfo.model;

          // 索引调整：Excel是从1开始，x-data-spreadsheet是从0开始
          const adjustedTop = top - 1;
          const adjustedLeft = left - 1;
          const adjustedBottom = bottom - 1;
          const adjustedRight = right - 1;

          const startCol = numberToColumn(left);
          const endCol = numberToColumn(right);
          const mergeRange = `${startCol}${top}:${endCol}${bottom}`;
          data.merges.push(mergeRange);

          // 确保左上角单元格存在且有cells对象
          if (!data.rows[adjustedTop]) {
            data.rows[adjustedTop] = { cells: {} };
          } else if (!data.rows[adjustedTop].cells) {
            data.rows[adjustedTop].cells = {};
          }

          if (!data.rows[adjustedTop].cells[adjustedLeft]) {
            data.rows[adjustedTop].cells[adjustedLeft] = {};
          }

          // 设置合并属性 - 与原表保持一致
          data.rows[adjustedTop].cells[adjustedLeft].merge = [
            adjustedBottom - adjustedTop, // 行数(纵向)
            adjustedRight - adjustedLeft, // 列数(横向)
          ];
          // 处理合并区域内的非左上角单元格 - 添加样式定义但不添加内容
          for (let r = top; r <= bottom; r++) {
            for (let c = left; c <= right; c++) {
              if (r === top && c === left) continue; // 跳过左上角

              const adjustedR = r - 1;
              const adjustedC = c - 1;

              // 确保单元格对象存在
              if (!data.rows[adjustedR]) {
                data.rows[adjustedR] = { cells: {} };
              } else if (!data.rows[adjustedR].cells) {
                data.rows[adjustedR].cells = {};
              }

              // 添加空单元格但保留样式
              // data.rows[adjustedR].cells[adjustedC] = { style: 1 }; // 使用基本样式

              // 记录合并区域中的非左上角单元格，避免后续重复处理
              mergedCellsSet.add(`${r},${c}`);
            }
          }
          // 记录合并区域的边界信息
          mergeBoundaries.set(`${adjustedTop},${adjustedLeft}`, {
            top: adjustedTop,
            left: adjustedLeft,
            bottom: adjustedBottom,
            right: adjustedRight,
          });
        }
      });
    }

    // 处理单元格数据
    let maxCol = 0; // 新增：用于记录最大列数
    worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
      // 索引调整
      const adjustedRowNumber = rowNumber - 1;

      if (!data.rows[adjustedRowNumber]) {
        data.rows[adjustedRowNumber] = { cells: {} };
      } else if (!data.rows[adjustedRowNumber].cells) {
        data.rows[adjustedRowNumber].cells = {};
      }

      // 处理行高
      if (row.height) {
        data.rows[adjustedRowNumber].height = row.height;
      }

      // 使用includeEmpty参数确保处理所有单元格，包括空值单元格
      row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
        // 索引调整
        const adjustedColNumber = colNumber - 1;

        // 新增：更新最大列数
        maxCol = Math.max(maxCol, adjustedColNumber);

        // 如果是合并区域中的非左上角单元格，则跳过处理
        if (mergedCellsSet.has(`${rowNumber},${colNumber}`)) {
          return;
        }

        // 确保单元格对象存在
        if (!data.rows[adjustedRowNumber].cells[adjustedColNumber]) {
          data.rows[adjustedRowNumber].cells[adjustedColNumber] = {};
        }

        const cellData = data.rows[adjustedRowNumber].cells[adjustedColNumber];

        // 处理单元格值
        if (cell.value !== null && cell.value !== undefined) {
          // console.log('普通单元格:', cell.value.formula)
          if (cell.value.richText) {
            cellData.text = cell.value.richText.map((rt) => rt.text).join("");
          } else if (cell.value.text) {
            cellData.text = cell.value.text;
          } else if (cell.value.formula) {
            // 处理公式单元格 - 直接获取显示值
            console.log("公式单元格:", cell.value, cell.result);
            cellData.text = cell.value.result || ""; // 使用cell.text获取格式化后的显示值
          } else if (cell.value instanceof Date) {
            //根据 cell.style.numFmt 属性判断日期格式 返回日期字符串
            if (cell.style.numFmt === "mm-dd-yy") {
              cellData.text = cell.value.toLocaleDateString();
            } else if (cell.style.numFmt === "m/d/yy \"h\":mm") {
              cellData.text = cell.value.toLocaleString();
            }
          } else if (cell.value.sharedFormula) {
            // console.log('公式:', cell.value.result)
            cellData.text = cell.value.result || ""; // 使用cell.text获取格式化后的显示值
          } else {
            // 处理普通值（如数字、字符串等）
            cellData.text =
              cell.text ||
              (typeof cell.value === "object"
                ? JSON.stringify(cell.value)
                : cell.value.toString());
          }
        } else {
          // 空单元格设置为空字符串
          cellData.text = "";
        }

        if (cell.style) {
          // 创建样式对象
          const styleObj = {};
          let hasBorder = false;

          // 处理字体属性
          // 处理字体属性
          if (cell.style.font) {
            console.log("字体:",cell, cell.style.font);
            if (cell.style.font.bold) styleObj.font = { ...styleObj.font, bold: true };
            if (cell.style.font.italic) styleObj.font = { ...styleObj.font, italic: true };
            if (cell.style.font.underline) styleObj.underline = true;
            if (cell.style.font.strike) styleObj.strike = true;
            if (cell.style.font.size) styleObj.fontSize = cell.style.font.size; // Ensure font size is read
            if (cell.style.font.name) styleObj.fontName = cell.style.font.name;
            if (cell.style.font.color && cell.style.font.color.argb) {
              styleObj.color = `#${cell.style.font.color.argb.substring(2) || '000000'}`;
            }
          }

          // 处理对齐方式
          if (cell.style.alignment) {
            styleObj.align = cell.style.alignment.horizontal || "left";
            styleObj.valign = cell.style.alignment.vertical || "middle";
            if (cell.style.alignment.wrapText) styleObj.textwrap = true;
          }

          // 处理背景色
          if (
            cell.style.fill &&
            cell.style.fill.fgColor &&
            cell.style.fill.fgColor.argb
          ) {
            console.log("背景色:", cell.style.fill.fgColor.argb);
            styleObj.bgcolor = `#${cell.style.fill.fgColor.argb.substring(2) || "ffffff"}`;
          }

          // 处理边框 - 使用与原表相同的结构
          if (cell.style.border) {
            styleObj.border = {};
            const borders = ["top", "right", "bottom", "left"];

            // 边框样式映射
            const borderStyleMap = {
              thin: "thin",
              medium: "medium",
              thick: "thick",
              dotted: "dotted",
              dashed: "dashed",
              double: "double",
              hair: "thin",
              dashDot: "dashed",
              dashDotDot: "dashed",
              slantDashDot: "dashed",
              mediumDashed: "dashed",
              mediumDashDot: "dashed",
              mediumDashDotDot: "dashed",
            };

            // 检查当前单元格是否在合并区域内
            let isInMerge = false;
            let mergeBoundary = null;
            for (const [key, boundary] of mergeBoundaries.entries()) {
              if (
                adjustedRowNumber >= boundary.top &&
                adjustedRowNumber <= boundary.bottom &&
                adjustedColNumber >= boundary.left &&
                adjustedColNumber <= boundary.right
              ) {
                isInMerge = true;
                mergeBoundary = boundary;
                break;
              }
            }

            borders.forEach((side) => {
              const borderInfo = cell.border;
              if (borderInfo) {
                // 处理边框样式和颜色
                Object.keys(borderInfo).forEach((side) => {
                  const border = borderInfo[side];
                  if (border) {
                    const excelBorderStyle = border.style;
                    const mappedStyle =
                      borderStyleMap[excelBorderStyle] || "thin";

                    let borderColor = "#000000";
                    if (border.color && border.color.argb) {
                      const argb = border.color.argb;
                      if (argb.length === 8) {
                        borderColor = `#${argb.substring(2)}`;
                      } else {
                        console.warn("Invalid ARGB color format:", argb);
                      }
                    }

                    styleObj.border = styleObj.border || {};
                    styleObj.border[side] = [mappedStyle, borderColor];
                    hasBorder = true;
                  }
                });
              }
            });

            // 如果没有任何边框设置，则删除border对象
            if (Object.keys(styleObj.border).length === 0) {
              delete styleObj.border;
            }
          }

          // 即使单元格没有文本，只要有样式（特别是边框）就添加样式
          if (Object.keys(styleObj).length > 0 || hasBorder) {
            // 检查是否已存在相同的样式，避免重复
            const styleKey = JSON.stringify(styleObj);
            let styleIndex;

            if (styleMap.has(styleKey)) {
              styleIndex = styleMap.get(styleKey);
            } else {
              styleIndex = data.styles.length;
              data.styles.push(styleObj);
              styleMap.set(styleKey, styleIndex);
            }

            // 设置样式索引
            cellData.style = styleIndex;
          }
        }
      });
    });

    // 新增：调整列数设置
    data.cols.len = Math.max(data.cols.len, maxCol + 1);

    console.log("数据处理完成:", [data]);

    // 加载数据到电子表格 - 注意要包装在数组中
    if (spreadsheet) {
      // 先清空当前数据
      spreadsheet.loadData([
        {
          name: "Sheet1",
          rows: { len: 5000 },
          cols: { len: 26 },
        },
      ]);

      // 然后加载处理后的数据 - 与原表相同的格式
      await spreadsheet.loadData([data]);
      spreadsheet.reRender();
    }
  } catch (error) {
    console.error("导入失败:", error);
    throw error;
  }
};
// 导出 Excel 文件
const exportExcel = async () => {
  try {
    const rawData = spreadsheet.getData();
    if (!rawData || !rawData.length) {
      throw new Error("没有可导出的数据");
    }

    console.log("原始数据:", rawData);
    const sheet = rawData[0];

    if (!sheet || !sheet.rows) {
      throw new Error("表格数据格式不正确");
    }

    // 获取最大行号和列号，同时检查每行是否有样式或内容
    let maxRow = 0;
    let maxCol = 0;
    const rowHasContent = new Set(); // 用于记录哪些行有内容或样式

    // 先遍历一遍找出实际的最大行和列，并标记有内容的行
    Object.entries(sheet.rows).forEach(([rowKey, row]) => {
      if (rowKey === "len") return;
      const rowIndex = parseInt(rowKey);

      if (row.cells) {
        let hasContent = false;
        Object.entries(row.cells).forEach(([colKey, cell]) => {
          if (colKey === "len") return;
          const colIndex = parseInt(colKey);

          // 检查单元格是否有内容或样式
          const hasStyle =
            cell.style && sheet.styles && sheet.styles[cell.style];
          if ((cell.text !== undefined && cell.text !== "") || hasStyle) {
            hasContent = true;
            maxRow = Math.max(maxRow, rowIndex + 1); // 确保行索引从1开始
            maxCol = Math.max(maxCol, colIndex + 1); // 确保列索引从1开始
          }
        });
        if (hasContent) {
          rowHasContent.add(rowIndex);
        }
      }
    });

    console.log("实际数据最大行数:", maxRow, "最大列数:", maxCol);

    // 如果没有找到任何数据，至少保留第一行
    if (maxRow === 0) maxRow = 1;
    if (maxCol === 0) maxCol = 1;

    // 创建新的工作簿
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet(sheet.name || "Sheet1");

    // 先创建所有需要的行
    for (let i = 1; i <= maxRow; i++) {
      worksheet.getRow(i);
    }

    // 处理每一行
    Object.entries(sheet.rows).forEach(([rowKey, row]) => {
      if (rowKey === "len") return;
      const rowIndex = parseInt(rowKey);

      // 只处理有内容或样式的行，且不超过最大行数
      if (!rowHasContent.has(rowIndex) || rowIndex + 1 > maxRow) return;

      const excelRow = worksheet.getRow(rowIndex + 1); // 确保行索引从1开始

      // 设置行高
      if (row.height) {
        excelRow.height = row.height;
      }

      if (row.cells) {
        Object.entries(row.cells).forEach(([colKey, cell]) => {
          if (colKey === "len") return;
          const colIndex = parseInt(colKey);

          // 只处理不超过最大列数的单元格，并确保列索引从1开始
          if (colIndex + 1 > maxCol) return;

          const excelCell = excelRow.getCell(colIndex + 1); // 确保列索引从1开始

          // 设置单元格值，只保存文本值
          if (cell.text !== undefined) {
            excelCell.value = cell.text;
          } else {
            excelCell.value = "";
          }

          // 获取样式定义
          if (
            typeof cell.style === "number" &&
            sheet.styles &&
            sheet.styles[cell.style]
          ) {
            const styleDefinition = sheet.styles[cell.style];

            // 处理字体
            if (styleDefinition.font) {
              excelCell.font = {
                name: styleDefinition.font.name || "Arial",
                size: styleDefinition.font.size || 11,
                bold: styleDefinition.font.bold || false,
                italic: styleDefinition.font.italic || false,
              };
            }

            // 处理下划线和删除线
            if (styleDefinition.underline || styleDefinition.strike) {
              if (!excelCell.font) excelCell.font = {};
              excelCell.font.underline = styleDefinition.underline || false;
              excelCell.font.strike = styleDefinition.strike || false;
            }

            // 处理字体颜色
            if (styleDefinition.color) {
              if (!excelCell.font) excelCell.font = {};
              excelCell.font.color = {
                argb: "FF" + tinycolor(styleDefinition.color).toHex(),
              };
            }

            // 处理背景色
            if (styleDefinition.bgcolor) {
              excelCell.fill = {
                type: "pattern",
                pattern: "solid",
                fgColor: {
                  argb: "FF" + tinycolor(styleDefinition.bgcolor).toHex(),
                },
              };
            }

            // 处理对齐方式
            excelCell.alignment = {
              horizontal: styleDefinition.align || "left",
              vertical: styleDefinition.valign || "middle",
              wrapText: styleDefinition.textwrap || false,
            };

            // 处理边框
            if (styleDefinition.border) {
              const border = {};
              Object.entries(styleDefinition.border).forEach(
                ([side, [style, color]]) => {
                  border[side] = {
                    style: style || "thin",
                    color: { argb: "FF" + tinycolor(color).toHex() },
                  };
                },
              );
              excelCell.border = border;
            }
          }
        });
      }
    });

    // 处理合并单元格
    if (sheet.merges) {
      sheet.merges.forEach((mergeStr) => {
        console.log("合并区域:", mergeStr);
        try {
          worksheet.mergeCells(mergeStr);
        } catch (error) {
          console.warn(`无法合并单元格 ${mergeStr}:`, error.message);
        }
      });
    }

    // 设置列宽
    if (sheet.cols) {
      Object.entries(sheet.cols).forEach(([colKey, col]) => {
        if (colKey !== "len" && col.width) {
          const colIndex = parseInt(colKey) + 1; // 确保列索引从1开始
          if (colIndex <= maxCol) {
            // 确保不超过最大列数
            const column = worksheet.getColumn(colIndex);
            if (column) {
              column.width = col.width / 6;
            }
          }
        }
      });
    }

    // 导出文件
    const buffer = await workbook.xlsx.writeBuffer();
    const blob = new Blob([buffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "spreadsheet.xlsx";
    link.click();
    window.URL.revokeObjectURL(url);

    console.log("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    alert(`导出失败: ${error.message || "请检查数据是否正确"}`);
  }
};

// 保存到本地存储
const saveToLocal = () => {
  const request = indexedDB.open("SpreadsheetDB", 1);

  request.onupgradeneeded = (event) => {
    const db = event.target.result;
    if (!db.objectStoreNames.contains("spreadsheet")) {
      db.createObjectStore("spreadsheet", { keyPath: "id" });
    }
  };

  request.onsuccess = (event) => {
    const db = event.target.result;
    const transaction = db.transaction(["spreadsheet"], "readwrite");
    const store = transaction.objectStore("spreadsheet");

    const data = { id: "spreadsheetData", content: spreadsheet.getData() };

    const putRequest = store.put(data);

    putRequest.onsuccess = () => {
      alert("数据保存成功");
    };

    putRequest.onerror = (error) => {
      console.error("保存数据失败:", error);
      alert("保存失败: " + error.target.error.message);
    };
  };

  request.onerror = (error) => {
    console.error("IndexedDB 打开失败:", error);
    alert("保存失败: " + error.target.error.message);
  };
};

// 从本地存储加载
const loadFromLocal = () => {
  const request = indexedDB.open("SpreadsheetDB", 1);

  request.onsuccess = (event) => {
    const db = event.target.result;
    const transaction = db.transaction(["spreadsheet"], "readonly");
    const store = transaction.objectStore("spreadsheet");

    const getRequest = store.get("spreadsheetData");

    getRequest.onsuccess = () => {
      const data = getRequest.result;
      if (data && data.content) {
        spreadsheet.loadData(data.content);
        console.log("已加载保存的数据", data.content);
      } else {
        spreadsheet.loadData(props.initialData);
      }
    };

    getRequest.onerror = (error) => {
      spreadsheet.loadData(props.initialData);
      alert("加载失败: " + error.target.error.message);
    };
  };

  request.onerror = (error) => {
    console.error("IndexedDB 打开失败:", error);
    alert("加载失败: " + error.target.error.message);
  };
};

// 清空当前表格
const clearSheet = () => {
  if (!spreadsheet) return;

  try {
    if (confirm("确定要清空当前表格吗？此操作不可恢复！")) {
      // 创建一个空的数据结构
      const emptyData = [
        {
          name: "Sheet1",
          rows: {},
          cols: {},
          styles: [],
          merges: [],
        },
      ];

      // 重置表格数据
      spreadsheet.loadData(emptyData);
      console.log("表格已清空");

      // 触发数据更新
      emit("update:data", emptyData);
    }
  } catch (error) {
    console.error("清空表格失败:", error);
    alert("清空表格失败: " + error.message);
  }
};
</script>

<style scoped>
.spreadsheet-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-save {
  background-color: #2196f3;
}

.btn-save:hover {
  background-color: #1976d2;
}

.btn-load {
  background-color: #ff9800;
}

.btn-load:hover {
  background-color: #f57c00;
}

.btn-clear {
  background-color: #9e9e9e;
}

.btn-clear:hover {
  background-color: #757575;
}

.btn-danger {
  background-color: #dc3545;
}

.btn-danger:hover {
  background-color: #c82333;
}

.btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.btn:hover:not(:disabled) {
  background-color: #45a049;
}

#spreadsheet {
  flex: 1;
  border: 1px solid #ddd;
  border-radius: 4px;

}

.spreadsheet-container{
  height: calc(100vh - 100px);
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #ffffff;
  border-top: 2px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
